package kuaishou

import (
	"GoServer/common"
	"GoServer/message"
	"GoServer/net"
	"GoServer/net/ws"
	"GoServer/utils/config"
	"GoServer/utils/debug"
	"GoServer/utils/tool"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

type Executor struct{}

type BindLiveRoomRequest struct {
	RoomCode   string `json:"roomCode"`
	Timestamp  uint64 `json:"timestamp"`
	ModuleType string `json:"moduleType"`
	ActionType string `json:"actionType"`
	Data       string `json:"data"`
	Sign       string `json:"sign"`
}
type BindLiveCallback struct {
	CallBackUrl string `json:"callBackUrl"`
}

type BindLiveRoomResponse struct {
	Result   int    `json:"result"`
	ErrorMsg string `json:"errorMsg"`
	Data     string `json:"data"`
}

func (e *Executor) StartLiveTask(roomId, msgType, gameName string) ([]byte, error) {
	return StartLiveTask(roomId, msgType, gameName, "start")
}

func (e *Executor) StopLiveTask(roomId, msgType, gameName string) ([]byte, error) {
	return StartLiveTask(roomId, msgType, gameName, "stop")
}

func StartLiveTask(roomId string, msgType string, gameName string, actionType string) ([]byte, error) {
	return BeginLiveTask(roomId, msgType, gameName, actionType)
}

func BeginLiveTask(roomId string, msgType string, gameName string, actionType string) ([]byte, error) {

	headers := map[string]string{
		"Content-Type": "application/json;charset=UTF-8",
	}

	testCallback := BindLiveCallback{
		CallBackUrl: "https://xp.mengzhugame.top/ks_ttxsgame/live/ks/live_message",
	}
	callbackJson, _ := json.Marshal(testCallback)

	now := uint64(time.Now().UnixMilli())
	tempRequst := map[string]any{
		"app_id":     config.GetConfig("app").GetString(common.GameName + ".appid"),
		"roomCode":   roomId,
		"timestamp":  now,
		"moduleType": "bind",
		"actionType": actionType,
		"data":       string(callbackJson),
	}

	sign := CalcSign(tempRequst, config.GetConfig("app").GetString(common.GameName+".appSecret"))

	timestampVal := tool.GetUint64FromMap(tempRequst, "timestamp")
	request := BindLiveRoomRequest{
		RoomCode:   roomId,
		Timestamp:  timestampVal,
		ModuleType: "bind",
		ActionType: actionType,
		Data:       string(callbackJson),
		Sign:       sign,
	}

	reqBody, err := json.Marshal(request)
	if err != nil {
		// 监听事件失败， 返回给客户端
		return nil, errors.New("StartLiveTask httpPost err:" + err.Error())
	}
	jsonStr := string(reqBody)
	debug.Logln(debug.Debug, "请求开通直播间互动任务：", jsonStr)

	params := map[string]string{
		"app_id":       config.GetConfig("app").GetString(common.GameName + ".appid"),
		"access_token": GetKSAccessToken(common.GameName),
	}
	finalURL := tool.BuildURL(config.GetConfig("app").GetString("kuaishou.bindLive"), params)
	res, err := tool.SendPostOnceRetry(finalURL, jsonStr, headers)
	if err != nil {
		// 监听事件失败， 返回给客户端
		return nil, errors.New("StartLiveTask httpPost err:" + err.Error())
	}
	msg := BindLiveRoomResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Warn, fmt.Sprintf("json 解析失败: %s", err))
		return nil, errors.New("启动任务，解析json数据失败")
	}
	if msg.Result != 1 {
		return nil, errors.New(fmt.Sprintf("启动任务，解析json数据失败: %s", msg.ErrorMsg))
	}

	debug.Logln(debug.Info, fmt.Sprintf("开启直播返回数据: %+v", msg))

	client := &ws.LiveInteractiveData{
		Message: message.Message{
			MsgType: message.SC_KS_AnchorInfo, // ⬅️ 替换成你系统定义的评论消息类型
			RoomId:  roomId,
		},
		Data: msg.Data,
	}
	if ws.IsRoomID(roomId) {
		client.SendToClient(roomId)
	} else {
		reqBody, _ := json.Marshal(msg)
		debug.Logln(debug.Info, "[评论消息]没有找到此玩家的连接，广播给其他服务器:", string(reqBody))
		net.BroadcastMessage("live-message", string(reqBody))
	}

	return res, nil
}
